# -*- coding: utf-8 -*-
'''
Created on 2013-4-11
@author: cl.lam
'''

import traceback
from flask import current_app as app
from flask import g, render_template, flash, session, redirect, url_for, request
from flask.blueprints import Blueprint
from sqlalchemy.sql.expression import and_, not_


from sys2do.views import BasicView
from sys2do.util.decorator import templated, loginRequired, activetab
from sys2do.util.common import _g, _gld
from sys2do.constant import MSG_SAVE_SUCC, TAB_BASIC, TAB_FLAG, LOG_TYPE_CREATE, \
    MESSAGE_INFO, MSG_SERVER_ERROR, MESSAGE_ERROR, MSG_NO_ID_SUPPLIED, \
    MSG_RECORD_NOT_EXIST, MSG_UPDATE_SUCC, LOG_TYPE_UPDATE, \
    MSG_RECORD_ALREADY_EXIST, MSG_SAME_NAME_RECORD_EXIST
from sys2do.model import Paytype, SysLog, qry, db
from sys2do.util.logic_helper import makeUpdateLog



__all__ = ['bpPtp']

bpPtp = Blueprint( 'bpPtp', __name__ )
@bpPtp.before_request
def addActivetab():    session[TAB_FLAG] = TAB_BASIC


class PaytypeView( BasicView ):

    template_folder = "mas.ptp"

    dbclz = Paytype

    @templated( "index.html" )
    @loginRequired
    def index( self ):
        form = SrhForm( request.form )
        form.url = url_for( '.view' )

        cds = [ self.dbclz.active == 0, ]
        if form.no.data : cds.append( self.dbclz.no.like( '%%%s%%' % form.no.data ) )
        if form.name.data : cds.append( self.dbclz.name.like( '%%%s%%' % form.name.data ) )
        if form.createTimeFrom.data : cds.append( self.dbclz.createTime > form.createTimeFrom.data )
        if form.createTimeTo.data : cds.append( self.dbclz.createTime < form.createTimeTo.data )

        result = qry( self.dbclz ).filter( and_( *cds ) ).order_by( self.dbclz.createTime )
        return {'result' : result , 'form' : form}


    @templated( 'view.html' )
    def view( self ):
        cid = _g( 'id' )
        if not cid :
            flash( MSG_NO_ID_SUPPLIED, MESSAGE_ERROR )
            return redirect( url_for( ".view" ) )

        obj = self.dbclz.get( cid )
        if not obj :
            flash( MSG_RECORD_NOT_EXIST, MESSAGE_ERROR )
            return redirect( url_for( ".view" ) )
        return {'obj' : obj}





    @templated( "add.html" )
    @loginRequired
    def add( self ):
        if request.method != 'POST': return {}
        params = _gld( 'name', 'remark' )

        if self._isDuplicate( params['name'] ) : return redirect( url_for( '.view', action = 'add' ) )

        try:
            obj = self.dbclz.create( params )
            db.add( obj )
            db.flush()
            db.add( SysLog( refClz = obj.__class__.__name__, type = LOG_TYPE_CREATE, refID = obj.id, ) )
            db.commit()
            flash( MSG_SAVE_SUCC, MESSAGE_INFO )
        except:
            traceback.print_exc()
            db.rollback()
            flash( MSG_SERVER_ERROR, MESSAGE_ERROR )
        return redirect( url_for( ".view" ) )


    @templated( "update.html" )
    @loginRequired
    def update( self ):
        cid = _g( 'id' )
        if not cid :
            flash( MSG_NO_ID_SUPPLIED, MESSAGE_ERROR )
            return redirect( url_for( ".view" ) )

        obj = self.dbclz.get( cid )
        if not obj :
            flash( MSG_RECORD_NOT_EXIST, MESSAGE_ERROR )
            return redirect( url_for( ".view" ) )

        if request.method != 'POST': return {'obj' : obj}

        try:
            oldCopy = obj.serialize()
            params = _gld( 'name', 'remark' )
            obj.update( params )
            newCopy = obj.serialize()
            makeUpdateLog( obj, oldCopy, newCopy )
            db.commit()
            flash( MSG_UPDATE_SUCC, MESSAGE_INFO )
        except:
            db.rollback()
            flash( MSG_SERVER_ERROR, MESSAGE_ERROR )
        return redirect( url_for( ".view", action = "view", id = obj.id ) )



    @templated( 'view_log.html' )
    def viewLog( self ):
        id = _g( 'id' )
        if not id : abort( 404 )
        obj = self.dbclz.get( id )
        if not obj : abort( 404 )
        return {'obj' : obj}



    def _isDuplicate( self, name ):
        try:
            qry( self.dbclz ).filter( self.dbclz.name == name ).one()
        except:
            return False
        else:
            flash( MSG_SAME_NAME_RECORD_EXIST, MESSAGE_ERROR )
            return True


bpPtp.add_url_rule( '/', view_func = PaytypeView.as_view( 'view' ), defaults = {'action':'index'} )
bpPtp.add_url_rule( '/<action>', view_func = PaytypeView.as_view( 'view' ) )

#===============================================================================
# form class
#===============================================================================

from wtforms import Form, TextField
from sys2do.util.wt_helper import MyDateField

class SrhForm( Form ):
    no = TextField( u'系统编号', )
    name = TextField( u'支付方式', )
    createTimeFrom = MyDateField( u'创建时间(开始)' )
    createTimeTo = MyDateField( u'创建时间(结束)' )
